#include "userresetpw.h"
#include "ui_userresetpw.h"
#include "userlogger.h"

UserResetPW::UserResetPW(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserResetPW)
{
    ui->setupUi(this);
    bdf = BllDataFlow::getInstance();
    sqlHelper = SqlHelper::getInstance();

    //Signals and Slots
    connect(bdf, &BllDataFlow::sendResetPwUserSignal, this, &UserResetPW::setUser);
    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &UserResetPW::retranslateUiSlot);

    initWidget();
}

UserResetPW::~UserResetPW()
{
    delete ui;
}

void UserResetPW::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    QPainter painter(this);
    painter.fillRect(this->rect(), QColor(255, 255, 255, 0));
}

void UserResetPW::on_btnClose_clicked()
{
    this->hide();
}

void UserResetPW::retranslateUiSlot()
{
    ui->retranslateUi(this);
    ui->labelTips->setText(tr("reset the password?"));
}

void UserResetPW::on_btnOK_clicked()
{
    user.password = USER_INIT_PASSWORD;

    bool ret = resetUser();
    if (ret)
    {
        UserLogger::log(QString(tr("Reset password for %1")).arg(user.name));

        this->hide();

        QString tips = tr("Reset Success") ;
        QString color = ret ? "#1e2b58" : "rgb(255, 0, 0)";

        MsgBox msgBox;
        msgBox.setTitle(tr("Reset Password"));
        QString html = QString("<p><span style='color: %2; font-size: 24px;'>%1</span></p>").arg(tips).arg(color);
        msgBox.setText(html);
        msgBox.setInformativeText(QString(tr("current password：%1")).arg(user.password));
        msgBox.setBtnCancelVisible(false);
        msgBox.exec();
    }
    else
    {
        UserLogger::log(QString(tr("Failed to Reset password for %1")).arg(user.name));
        MsgBox::information(this, QString(tr("Reset Password: %1")).arg(user.name), QString(tr("%1 to Reset Password")).arg(tr("Failed")));
    }
}

void UserResetPW::setUser(User user)
{
    this->user = user;
}

void UserResetPW::initWidget()
{
    setAttribute(Qt::WA_TranslucentBackground, true);
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
    shadow->setColor(QColor(0, 0, 0, 150));
    shadow->setOffset(1, 1);
    shadow->setBlurRadius(16);
    ui->widget_2->setGraphicsEffect(shadow);
    ui->labelTips->setText(tr("reset the password?"));
}

bool UserResetPW::resetUser()
{
    EttaError ret;
    // 先重置密码
    ret = sqlHelper->setUserPassword(user);
    if (EttaError::OK == ret)
    {//再重置失败次数
        ret = sqlHelper->setFailLoginTimes(user);
    }

    return (EttaError::OK == ret);
}

void UserResetPW::on_btnCancle_clicked()
{
    this->hide();
}

